let controller; // 用于取消 fetch 请求
let eventSource; // 用于存储 EventSource 实例

function showLoading() {
    const resultDiv = document.getElementById('result');
    resultDiv.innerHTML = '正在执行，请稍候...';
    resultDiv.textContent = ''; // 清空之前的结果
    document.getElementById('cancelButton').style.display = 'inline-block';
}

function changeFunction() {
    const func = document.getElementById('function').value;
    document.getElementById('pingInputs').style.display = func === 'ping' ? 'block' : 'none';
    document.getElementById('tcpInputs').style.display = func === 'tcptraceroute' ? 'block' : 'none';
}

function executeFunction() {
    const func = document.getElementById('function').value;
    const destination = document.getElementById('destination').value || '8.8.8.8';
    
    showLoading();

    let url = '';
    switch(func) {
        case 'ping':
            const count = document.getElementById('pingCount').value || '4';
            url = `/ping?dest=${destination}&count=${count}`;
            break;
        case 'traceroute':
            url = `/traceroute?dest=${destination}`;
            break;
        case 'tcptraceroute':
            const port = document.getElementById('tcpPort').value || '80';
            url = `/tcptraceroute?dest=${destination}&port=${port}`;
            break;
    }

    // 创建 EventSource 连接
    eventSource = new EventSource(url);

    // 监听消息事件
    eventSource.onmessage = function(event) {
        const resultDiv = document.getElementById('result');
        resultDiv.textContent += event.data + '\n';
        resultDiv.scrollTop = resultDiv.scrollHeight; // 自动滚动到底部
    };

    // 监听错误事件
    eventSource.onerror = function() {
        document.getElementById('result').textContent += '\n操作已完成或已取消';
        document.getElementById('cancelButton').style.display = 'none';
        eventSource.close();
    };
}

function cancelFunction() {
    if (eventSource) {
        eventSource.close(); // 关闭 EventSource 连接
        document.getElementById('result').textContent += '\n操作已取消';
        document.getElementById('cancelButton').style.display = 'none';
    }
}